package com.fwtai.quartz;

import com.fwtai.service.SpringContextHolder;
import com.fwtai.web.TaskHandlerDao;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@EnableScheduling
public class QuartzDeleteOrder implements Job{

  public final static String groupDeleteOrder = QuartzDeleteOrder.class.getName();//用于删除延时任务

  public final static String dateKey = "kid";//数据key的标识

  @Override
  public void execute(final JobExecutionContext context){
    final JobDetail jobDetail = context.getJobDetail();
    final JobDataMap jobDataMap = jobDetail.getJobDataMap();
    final Long orderId = jobDataMap.getLong(dateKey);
    final TaskHandlerDao taskHandlerDao = SpringContextHolder.getBean(TaskHandlerDao.class);
    final Long orderKey = taskHandlerDao.getOrderStatus(orderId);//查询是否为未支付的订单id,此行可以不用,但此方法比较保险
    if(orderKey != null && orderKey.equals(orderId)){
      final List<Long> list = new ArrayList<>(1);
      list.add(orderKey);
      final int rows = taskHandlerDao.delTimeoutOrder(list);
      if(rows > 0){
        delOrderHandler(orderId);
      }
    }else{
      delOrderHandler(orderId);
    }
  }

  //移除一个任务,ok
  public void delOrderHandler(final Long value){
    try {
      final String jobName = String.valueOf(value);
      final SchedulerFactory schedulerFactory = new StdSchedulerFactory();//创建调度器Scheduler
      final Scheduler scheduler = schedulerFactory.getScheduler();
      final TriggerKey triggerKey = new TriggerKey(jobName,groupDeleteOrder);
      scheduler.pauseTrigger(triggerKey);//停止指定的name和group的触发器
      scheduler.unscheduleJob(triggerKey);//移除触发器
      scheduler.deleteJob(new JobKey(jobName,groupDeleteOrder));//删除任务
    } catch (final SchedulerException exception){
      exception.printStackTrace();
    }
  }
}